﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Telerik.Web.UI;

namespace Medianamik.UI.Web.DB
{
    public partial class Default : System.Web.UI.Page
    {
        private RadGrid _schemaChangeGrid = null;
        protected void Page_Init(object sender, EventArgs e)
        {
            BuildPage();
        }

        private void BuildPage()
        {
            _schemaChangeGrid = BuildGrid();

            var html = new System.Web.UI.HtmlControls.HtmlGenericControl("html");
            var head = new System.Web.UI.HtmlControls.HtmlHead("head");
            var title = new System.Web.UI.HtmlControls.HtmlGenericControl("title") { InnerText = "Title" };
            var form = new System.Web.UI.HtmlControls.HtmlForm();
            var body = new System.Web.UI.HtmlControls.HtmlGenericControl("body");
            var scriptManager = new RadScriptManager();
            
            
            form.Controls.Add(scriptManager);
            var div1 = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
            
            var applyAllButton = new Button()
            {
                ID="btnApplyAll",
                Text ="(^_^);;"
            };
            applyAllButton.Click  += btnApplyAll_Click;

            div1.Controls.Add(new LiteralControl("Apply all available change scripts "));
            div1.Controls.Add(applyAllButton);
            form.Controls.Add(div1); 
            
            form.Controls.Add(_schemaChangeGrid);
            body.Controls.Add(form);
            html.Controls.Add(head);
            html.Controls.Add(body);
            Page.Controls.Add(html);
            
        }

        private RadGrid BuildGrid()
        {
            var grid = new RadGrid()
            {
                ID = "SchemaChangeGrid",
                AutoGenerateColumns = false,
            };
            grid.ItemCommand += SchemaChangeGrid_ItemCommand;
            grid.NeedDataSource += SchemaChangeGrid_NeedDataSource;

            var majorReleaseColumn = new GridBoundColumn()
            {
                DataField = "MajorReleaseNumber",
                HeaderText = "Major Release"
            };
            var minorReleaseColumn = new GridBoundColumn()
            {
                DataField = "MinorReleaseNumber",
                HeaderText = "Minor Release"
            };
            var pointReleaseColumn = new GridBoundColumn()
            {
                DataField = "PointReleaseNumber",
                HeaderText = "Point Release"
            };
            var scriptNameColumn = new GridBoundColumn()
            {
                DataField = "ScriptName",
                HeaderText = "Script Name"
            };
            var dateAppliedColumn = new GridTemplateColumn()
            {
                HeaderText = "Date Applied",
                ItemTemplate = new DateAppliedItemTemplate()
            };
            var actionsColumn = new GridTemplateColumn()
            {
                HeaderText = "Actions",
                ItemTemplate = new ActionItemTemplate()
            };
            var columns = grid.MasterTableView.Columns;
            columns.Add(majorReleaseColumn);
            columns.Add(minorReleaseColumn);
            columns.Add(pointReleaseColumn);
            columns.Add(scriptNameColumn);
            columns.Add(dateAppliedColumn);
            columns.Add(actionsColumn);

            return grid;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                _schemaChangeGrid.DataBind();
            }
        }
        
        protected void SchemaChangeGrid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            _schemaChangeGrid.DataSource = ConfigManager.GetSchemaChangesMerged();
        }

        protected void SchemaChangeGrid_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            switch (e.CommandName.ToLower())
            {
                case "apply":
                    ConfigManager.ApplySchemaChange(ConfigManager.GetSchemaChangeFromScriptName((string)e.CommandArgument));
                    break;
                case "show":
                    string content = ConfigManager.GetSchemaChangeContent(ConfigManager.GetSchemaChangeFromScriptName((string)e.CommandArgument));
                    Response.Clear();
                    Response.ContentType = "text/plain";
                    Response.Write(content);
                    Response.End();
                    break;
                default:
                    break;
            }

            _schemaChangeGrid.Rebind();


        }

        protected void btnApplyAll_Click(object sender, EventArgs e)
        {
            var changes = ConfigManager.GetSchemaChangesMerged()
                .Where(c => !c.DateApplied.HasValue);

           foreach (var change in changes)
           {
               ConfigManager.ApplySchemaChange(change);
           }

           _schemaChangeGrid.Rebind();
        }

        private class ActionItemTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                var cell = container as GridTableCell;

                var applyButton = new Button()
                {
                    ID = "btnApply",
                    CommandName = "apply",
                    Text = "Apply"
                };
                

                var showButton = new Button()
                {
                    ID = "btnShow",
                    CommandName = "show",
                    Text = "Show"
                };
                
                applyButton.DataBinding += new EventHandler(Button_DataBinding);
                showButton.DataBinding += new EventHandler(Button_DataBinding);

                container.Controls.Add(applyButton);
                container.Controls.Add(showButton);

            }

            void Button_DataBinding(object sender, EventArgs e)
            {
                var button = (Button)sender;
                var gridItem = (GridItem)button.BindingContainer;
                 button.CommandArgument = (string)DataBinder.Eval(gridItem.DataItem , "ScriptName");
                 button.Enabled = (bool)DataBinder.Eval(gridItem.DataItem, "ResourceExists");
            }
        }

        private class DateAppliedItemTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                var content = new Literal();
                content.DataBinding += new EventHandler(content_DataBinding);
                container.Controls.Add(content);
                
            }

            void content_DataBinding(object sender, EventArgs e)
            {
                var content = (Literal)sender;
                var gridItem = (GridItem)content.BindingContainer;
               
                var dateApplied = (DateTime?)DataBinder.Eval(gridItem.DataItem , "DateApplied");
                content.Text = dateApplied.HasValue ? dateApplied.Value.ToString("yyyy-MM-dd HH:mm:ss") :string.Empty; 
            }
        }
    }
}
